package cn.uil.demo2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.SmartLifecycle;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

@Component
public class AsyncBeanInitializer implements SmartLifecycle {

    private volatile boolean isRunning = false;
    private final ApplicationContext applicationContext;
    private final Set<String> asyncBeanNames;
    private final Executor taskExecutor; // 注入异步线程池

    @Autowired
    public AsyncBeanInitializer(
            ApplicationContext applicationContext,
            Set<String> asyncBeanNames,
            Executor taskExecutor // 需配置异步线程池
    ) {
        this.applicationContext = applicationContext;
        this.asyncBeanNames = asyncBeanNames;
        this.taskExecutor = taskExecutor;
    }

    @Override
    public void start() {
        if (!isRunning) {
            isRunning = true;
            // 提交异步任务初始化Bean
            CompletableFuture.runAsync(this::initializeAsyncBeans, taskExecutor);
        }
    }

    @Async // 使用异步执行
    public void initializeAsyncBeans() {
        for (String beanName : asyncBeanNames) {
            // 显式调用getBean()触发Bean初始化
            applicationContext.getBean(beanName);
            System.out.println("Asynchronously initialized: " + beanName);
        }
    }

    @Override
    public void stop() {
        isRunning = false;
    }

    @Override
    public boolean isRunning() {
        return isRunning;
    }

    // 设置高优先级确保在Spring Boot完全启动后执行
    @Override
    public int getPhase() {
        return Integer.MAX_VALUE;
    }
}
